package com.blueocean_health.care.management.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.blueocean_health.care.management.common.LocalManager;
import com.blueocean_health.care.management.common.base.string.StringUtils;
import com.blueocean_health.care.management.domain.base.SysResult;
import com.blueocean_health.care.management.domain.base.UserPatient;
import com.blueocean_health.care.management.em.LocalManagerType;
import com.blueocean_health.care.management.service.UserPatientService;

/**
 * 用户校验拦截器
 */
//@Interceptor(path = "/**", order = "1", excludePath = { "/userPatient/**","/error"})
@Component
public class AppValidateInterceptor implements HandlerInterceptor {
	@Resource
	private UserPatientService userService;

	@Override
	public boolean preHandle(HttpServletRequest request, 
			HttpServletResponse response, Object handler) throws Exception {
		String token = request.getHeader("token");
		String parameter = request.getParameter("token");
		if(!StringUtils.isEmpty(parameter)){
			token = parameter;
		}
//		System.out.println("token:"+token);
		// 根据userTokenKey获取userId
		UserPatient userPatient = null;
		try {
			userPatient = userService.getUserInfoByToken(token);
//			System.out.println("+++++++++"+user);
		} catch (Exception e) { 
			e.printStackTrace();
		}
		if (userPatient == null) {
			SysResult result = SysResult.error(SysResult.validateError, "用户验证失败");
			String json = JSONObject.toJSONString(result);//JsonSerializUtil.javaToJson(result);
			response.setCharacterEncoding("UTF-8");
			response.getWriter().print(json);
			return false;
		}
		request.setAttribute("userPatient", userPatient);
		LocalManager.setVal(LocalManagerType.USER_APP, userPatient);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// 7. 解除绑定
		//UserContext.getInstance().remove();
	}
}